package exam.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Scanner;


/*
 * 监听webSocket地址/myWS
 * */
@ServerEndpoint("/myWs")
@Component
@Slf4j
public class MyWebSocketServer {

//    private SocketServerListenHandler socketServerListenHandler;
//
//    @Autowired
//    public void setSocketServerListenHandler(SocketServerListenHandler socketServerListenHandler) {
//        this.socketServerListenHandler = socketServerListenHandler;
//    }
    static Map<String,Session> sessionMap = new ConcurrentHashMap<>();//存放多个WebSocket客户端
    private static Session session;
    private String mes;


    //连接建立时执行的操作
    @OnOpen
    public void onOpen(Session session){
        sessionMap.put(session.getId(),session);
        log.info("websocket is open");
        String speakerId = (String) session.getUserProperties().get("speakerId");

    }


    //收到了客户端消息执行的操作
    @OnMessage //监听通信
    public String onMessage(String text){
        log.info("收到了一条消息:"+text);
        //sendMessageToClients(text);
        SocketServerListenHandler.sendMessageToClients(text);
        return "已收到你的消息";
    }


    //连接关闭时执行的操作
    @OnClose
    public void onClose(Session session){
        sessionMap.remove(session.getId());
        log.info("webSocket is close");
    }
    //定时任务,每隔两秒给客户端发送一个心跳
    /*@Scheduled(fixedRate = 2000)
    public void sendMsg() throws IOException {
        for(String key:sessionMap.keySet()){
            sessionMap.get(key).getBasicRemote().sendText("心跳");
        }
    }
     */
    // 发送消息给连接的 WebSocket 客户端
    public void sendMessageToClients(String message) {
        // 遍历存储 WebSocket 客户端会话的 sessionMap
        for (String sessionId : sessionMap.keySet()) {
            Session session = sessionMap.get(sessionId);
            try {
                // 使用会话的 BasicRemote 发送消息给客户端
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("Error sending message to client with session ID: {}", sessionId, e);
            }
        }
    }

}
